package net.tv90.appserveradmin.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import net.tv90.appserveradmin.model.Checkitem;
import net.tv90.appserveradmin.model.CheckitemDetailed;
import net.tv90.appserveradmin.model.dto.CheckitemDTO;
import net.tv90.appserveradmin.service.CheckitemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/checkitems")
public class CheckitemController {

    @Autowired
    private CheckitemService checkitemService;

    @SaCheckRole("doctor")
    @GetMapping
    public String listCheckitems(Model model) {
        List<Checkitem> checkitemList = checkitemService.list();
        model.addAttribute("checkitems", checkitemList);
        return "checkitems/list";
    }

    @SaCheckRole("doctor")
    @GetMapping("/add")
    public String addCheckitemForm(Model model) {
        CheckitemDTO checkitemDTO = new CheckitemDTO();
        checkitemDTO.setCheckitem(new Checkitem());
        checkitemDTO.setCheckitemDetailed(new CheckitemDetailed());
        model.addAttribute("checkitemDTO", checkitemDTO);
        return "checkitems/add";
    }

    @SaCheckRole("doctor")
    @PostMapping("/add")
    public String addCheckitem(@ModelAttribute CheckitemDTO checkitemDTO) {
        checkitemService.save(checkitemDTO.getCheckitem(), checkitemDTO.getCheckitemDetailed());
        return "redirect:/checkitems";
    }

    @SaCheckRole("doctor")
    @GetMapping("/view/{id}")
    public String viewCheckitem(@PathVariable Long id, Model model) {
        Checkitem checkitem = checkitemService.getById(id);
        CheckitemDetailed checkitemDetailed = checkitemService.getByCiId(id);
        model.addAttribute("checkitem", checkitem);
        model.addAttribute("checkitemDetailed", checkitemDetailed);
        return "checkitems/view";
    }

    @SaCheckRole("doctor")
    @GetMapping("/edit/{id}")
    public String editCheckitemForm(@PathVariable Long id, Model model) {
        Checkitem checkitem = checkitemService.getById(id);
        CheckitemDetailed checkitemDetailed = checkitemService.getByCiId(id);
        CheckitemDTO checkitemDTO = new CheckitemDTO(checkitem, checkitemDetailed);
        model.addAttribute("checkitemDTO", checkitemDTO);
        return "checkitems/edit";
    }


    @SaCheckRole("doctor")
    @PostMapping("/edit")
    public String editCheckitem(@ModelAttribute CheckitemDTO checkitemDTO) {
        checkitemService.updateById(checkitemDTO.getCheckitem(), checkitemDTO.getCheckitemDetailed());
        return "redirect:/checkitems";
    }

    @SaCheckRole("doctor")
    @GetMapping("/delete/{id}")
    public String deleteCheckitem(@PathVariable Long id) {
        checkitemService.deleteById(id);
        return "redirect:/checkitems";
    }

}